package com.demo.randomdining

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.demo.randomdining.dao.TargetDB
import com.demo.randomdining.databinding.ActivityMainBinding
import com.demo.randomdining.databinding.TextItemViewBinding
import com.demo.randomdining.model.TargetInfo
import java.util.Random

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private val foodList = arrayListOf<String>()
    private val resultMap = mutableMapOf("" to 0)
    private val resultList = arrayListOf("")
    var adapter = RcvAdapter()

    private val mRandom = Random()

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val serializableExtra = intent?.getSerializableExtra("list")
        if (serializableExtra is ArrayList<*>) {
            foodList.clear()
            serializableExtra.forEach {
                if (it is TargetInfo) {
                    foodList.add(it.name)
                }
            }
            if (foodList.size == 0) {
                val all = TargetDB.getInstance(this).targetDao.getAll()
                all.forEach {
                    foodList.add(it.name)
                }
            }
            adapter.setList(foodList)
            adapter.notifyDataSetChanged()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.btnAdd.setOnClickListener {
            val trim = binding.etFood.text.toString().trim()
            if (TextUtils.isEmpty(trim)) {
                Toast.makeText(MainActivity@ this, "店名不能为空", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            adapter.add(trim)
            binding.etFood.text.clear()
        }

        binding.btnStart.setOnClickListener {
            val index = mRandom.nextInt(adapter.data.size)
            var food = adapter.data[index]
            resultMap.merge(food, 1, Int::plus)
            resultList.add(food)
            var str = ""
            resultMap.forEach { (t, u) ->
                if (!TextUtils.isEmpty(t)) {
                    str += "${t}：$u 次\n"
                }
            }
            resultList.forEachIndexed { index, s ->
                if (index != 0) {
                    str += "第${index}次结果为：$s \n"
                }
            }
            binding.tvRandomResult.text = str
        }

        binding.rcvFood.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding.rcvFood.adapter = adapter
        val all = TargetDB.getInstance(this).targetDao.getAll()
        all.forEach {
            foodList.add(it.name)
        }
        adapter.setList(foodList)
        binding.btnSelect.setOnClickListener {
            startActivity(Intent(MainActivity@ this, SelectActivity::class.java))
        }
    }


    class RcvAdapter : RecyclerView.Adapter<ViewHolder>() {
        var data = arrayListOf<String>()
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            return ViewHolder.from(parent)
        }

        public fun setList(data: List<String>) {
            this.data.clear()
            this.data.addAll(data)
            notifyDataSetChanged()
        }

        public fun add(str: String) {
            this.data.add(str)
            notifyDataSetChanged()
        }

        override fun getItemCount() = data.size

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val item = data[position]
            holder.bind(item, onClick)
        }

        var onClick = OnClickListener { v ->
            val tag = v?.getTag(Int.MIN_VALUE)
            if (tag is String) {
                data.remove(tag)
            }
            notifyDataSetChanged()
        }
    }

    class ViewHolder private constructor(val binding: TextItemViewBinding) : RecyclerView.ViewHolder(binding.root) {

        fun bind(item: String, onClick: OnClickListener) {
            binding.tvName.text = item
            binding.btnRemove.setTag(Int.MIN_VALUE, item)
            binding.btnRemove.setOnClickListener(onClick)
        }

        companion object {
            fun from(parent: ViewGroup): ViewHolder {
                val layoutInflater = LayoutInflater.from(parent.context)
                val binding = TextItemViewBinding.inflate(layoutInflater, parent, false)
                return ViewHolder(binding)
            }
        }
    }
}